package com.ruoyi.business.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OrderUtils;
import com.ruoyi.common.utils.SecurityUtils;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.BusShopMapper;
import com.ruoyi.business.domain.BusShop;
import com.ruoyi.business.service.IBusShopService;

/**
 * 商品Service业务层处理
 *
 * @author lzq
 * @date 2022-10-22
 */
@Service
public class BusShopServiceImpl implements IBusShopService {
    @Resource
    private BusShopMapper busShopMapper;

    /**
     * 查询商品
     *
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public BusShop selectBusShopById(Long id) {
        return busShopMapper.selectBusShopById(id);
    }

    /**
     * 查询商品列表
     *
     * @param busShop 商品
     * @return 商品
     */
    @Override
    public List<BusShop> selectBusShopList(BusShop busShop) {
        return busShopMapper.selectBusShopList(busShop);
    }

    /**
     * 新增商品
     *
     * @param busShop 商品
     * @return 结果
     */
    @Override
    public int insertBusShop(BusShop busShop) {
        busShop.setBarCode(OrderUtils.toCode(SecurityUtils.getUserId().intValue()));
        busShop.setCreateBy(SecurityUtils.getUsername());
        busShop.setCreateTime(DateUtils.getNowDate());
        return busShopMapper.insertBusShop(busShop);
    }

    /**
     * 修改商品
     *
     * @param busShop 商品
     * @return 结果
     */
    @Override
    public int updateBusShop(BusShop busShop) {
        busShop.setUpdateBy(SecurityUtils.getUsername());
        busShop.setUpdateTime(DateUtils.getNowDate());
        return busShopMapper.updateBusShop(busShop);
    }

    /**
     * 批量删除商品
     *
     * @param ids 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteBusShopByIds(Long[] ids) {
        return busShopMapper.deleteBusShopByIds(ids);
    }

    /**
     * 删除商品信息
     *
     * @param id 商品主键
     * @return 结果
     */
    @Override
    public int deleteBusShopById(Long id) {
        return busShopMapper.deleteBusShopById(id);
    }

    /**
     * 减少库存
     *
     * @param id     商品主键
     * @param number 数量
     * @return 结果
     */
    @Override
    public int reduceStock(Long id, Integer number) {
        BusShop busShop = this.selectBusShopById(id);
        if (busShop.getStock() > 0 && number > 0) {
            int stock = busShop.getStock() - number;
            if (stock >= 0) {
                busShop.setStock(stock);
            } else {
                busShop.setStock(0);
            }
        }
        return this.updateBusShop(busShop);
    }
}
